package container

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"ycontainer/cgroups"
)

type Record struct {
	Id              string                 `json:"id,omitempty"`
	Pid             int                    `json:"pid,omitempty"`
	Status          string                 `json:"status,omitempty"`
	CreateTime      string                 `json:"createTime,omitempty"`
	Name            string                 `json:"name,omitempty"`
	ImageName       string                 `json:"imageName,omitempty"`
	Detach          bool                   `json:"detach,omitempty"`
	StartCmdAndArgs []string               `json:"startCmdAndArgs,omitempty"`
	Volumes         []string               `json:"volumes,omitempty"`
	ResourceLimit   *cgroups.ResourceLimit `json:"resourceLimit,omitempty"`
}

var DefaultRecordFileName = "record.json"

func (c *Container) Record() {
	recordJson := buildRecordJson(c)

	file := createRecordFile(c)
	defer file.Close()

	if _, err := file.WriteString(recordJson); err != nil {
		logrus.Errorf("File write err: %v", err)
		return
	}
}

func (c *Container) RemoveRecord() {
	fullFilePath := path.Join(YcontainerRoot, "containers", c.Name)
	if err := os.RemoveAll(fullFilePath); err != nil {
		logrus.Errorf("remove record [%s] err: %v", fullFilePath, err)
		return
	}
}

func createRecordFile(c *Container) *os.File {
	fullDirPath := path.Join(YcontainerRoot, "containers", c.Name)

	if _, err := os.Stat(fullDirPath); err != nil {
		os.MkdirAll(fullDirPath, 0666)
	}

	fileName := path.Join(fullDirPath, DefaultRecordFileName)
	file, err := os.Create(fileName)
	if err != nil {
		logrus.Errorf("create file [%s] err: %v", fileName, err)
	}
	return file
}

func buildRecordJson(c *Container) string {
	record := buildRecord(c)

	bytes, err := json.Marshal(record)

	if err != nil {
		logrus.Errorf("record marshal err: %v", err)
	}
	return string(bytes)
}

func buildRecord(c *Container) *Record {
	return &Record{
		Id:              c.Id,
		Pid:             c.Pid,
		Status:          c.Status,
		CreateTime:      c.CreateTime,
		Name:            c.Name,
		ImageName:       c.ImageName,
		Detach:          c.Detach,
		StartCmdAndArgs: c.StartCmdAndArgs,
		Volumes:         c.Volumes,
		ResourceLimit:   c.ResourceLimit,
	}
}
